const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const tencentcloud = require('tencentcloud-sdk-nodejs')
const SmsClient = tencentcloud.sms.v20190711.Client
const clientConfig = {
  credential: {
    secretId: 'AKIDcLA7e8dzKWVK3a2IYp4FILH2azCnDUu8',
    secretKey: 'Let46AAGLOM9QVXVPFfw04tdH1lVMuQU',
  },
  region: 'ap-chengdu',
  profile: {
    httpProfile: {
      endpoint: 'sms.tencentcloudapi.com',
    },
  },
}
const client = new SmsClient(clientConfig)
const codeMap = {}
app.use(bodyParser.json())
app.use((req, res, next) => {
    // 允许所有的域名进行跨域请求
    res.setHeader('Access-Control-Allow-Origin', '*')
  
    // 允许所有的HTTP方法进行跨域请求
    res.setHeader('Access-Control-Allow-Methods', '*')
  
    // 允许所有的HTTP请求头进行跨域请求
    res.setHeader('Access-Control-Allow-Headers', '*')
  
    next()
  })
// 发送短信验证码的 API
app.post('/api/sendCode', (req, res) => {
  // 从请求体中获取手机号码
  const { phone } = req.body

  // 生成一个6位数的随机验证码
  const code = Math.floor(Math.random() * 1000000).toString().padStart(6, '0')
  console.log(phone,code)
  // 构造短信内容
  // const params = JSON.stringify([code, 5])
  const params = [code]
  codeMap[phone] = code
  // 调用腾讯云 SMS API 发送短信 
  const smsParams = {
    PhoneNumberSet: [`+86${phone}`], 
    TemplateID: "1758276",
    SmsSdkAppid: "1400810382", 
    Sign:"Canwin的数学小游戏",
    TemplateParamSet: params,
  }
  client.SendSms(smsParams, (err, response) => {
    if (err) {
      console.log(err)
      res.json({
        code: -1,
        message: '发送验证码失败',
      })
    } else {
      console.log(response)
      res.json({
        code: 0,
        message: '发送验证码成功',
      })
    }
  })
})

app.post('/api/verifyCode', (req, res) => {
  // 从请求体中获取手机号码和验证码
  const { phone, code } = req.body

  // 从 codeMap 中获取保存的验证码
  const savedCode = codeMap[phone]
console.log(code)
  if (savedCode && savedCode === code) {
    // 如果验证码正确，则清空 codeMap 中对应的验证码
    delete codeMap[phone]
    res.json({
      code: 0,
      message: '验证码正确',
    })
  } else {
    res.json({
      code: -1,
      message: '验证码错误',
    })
  }
})
app.listen(3001, () => {
  console.log('Server is running at http://localhost:3001')
})
